import { Spin, Switch, Button, App } from 'antd'
import { ImportantEditModal } from '@/desktop/components'
import services from '@/services'
import { Permission } from '@/services/auth'

export default function EditPermission(props: {
  isSuperAdmin: boolean // 当前操作者是否是超级管理员
  accountId: string | null
  onClose: () => void
}) {
  const { isSuperAdmin, accountId, onClose } = props

  return <ImportantEditModal
    title="权限设置"
    styleName="modal"
    open={accountId !== null}
    onCancel={onClose}
  >
    {accountId !== null ? (
      <Content isSuperAdmin={isSuperAdmin} accountId={accountId} onFinish={onClose} />
    ) : null}
  </ImportantEditModal>
}

function Content(props: {
  isSuperAdmin: boolean // 当前操作者是否是超级管理员
  accountId: string
  onFinish: () => void
}) {
  const { message } = App.useApp()
  const { isSuperAdmin: operatorIsSuperAdmin, accountId, onFinish } = props

  const [initialPermissions, setInitialPermissions] = useState<Permission[] | null>(null)
  const [permissions, setPermissions] = useState<Permission[]>([])
  const [saving, setSaving] = useState(false)

  const hasAdminPermission = permissions.includes(Permission.Admin)

  const load = useCallback(() => {
    void services.features.accounts.getPermissions(accountId).then(_permissions => {
      setInitialPermissions(_permissions)
      setPermissions(_permissions)
    })
  }, [accountId])
  useEffect(() => load(), [load])

  const switchPermission = useCallback(
    (permission: Permission) => {
      if (permissions.includes(permission))
        setPermissions(permissions.filter(v => v !== permission))
      else setPermissions([...permissions, permission])
    },
    [permissions],
  )

  const save = useCallback(async () => {
    if (!initialPermissions) return

    const adds = permissions.filter(permission => !initialPermissions.includes(permission))
    const removes = initialPermissions.filter(permission => !permissions.includes(permission))
    if (!adds.length && !removes.length) return void onFinish()

    setSaving(true)
    const results = await Promise.all([
      ...adds.map(async permission =>
        services.features.accounts.addPermission(accountId, permission),
      ),
      ...removes.map(async permission =>
        services.features.accounts.removePermission(accountId, permission),
      ),
    ])
    setSaving(false)

    for (const res of results) {
      if (!res.success) {
        void message.error(`权限保存失败：${res.error}`)
        load() // 刷新权限列表
        return
      }
    }
    void message.success('权限保存成功')
    onFinish()
  }, [message, initialPermissions, permissions, accountId, onFinish, load])

  return <Spin spinning={!initialPermissions} tip="加载中...">
    <main css={contentStyle}>
      <section>
        <label>主动转交客户聊天</label>
        <Switch
          checked={hasAdminPermission || permissions.includes(Permission.AnyTransfer)}
          onChange={() => switchPermission(Permission.AnyTransfer)}
          disabled={hasAdminPermission}
        />
        <div className="tips">
          开启该权限后，此账号可主动将他人的客户聊天转交给自己或其他账号，并进行聊天。
        </div>
      </section>

      {operatorIsSuperAdmin ? (
        <section>
          <label>管理员权限</label>
          <Switch
            checked={hasAdminPermission}
            onChange={() => switchPermission(Permission.Admin)}
          />
          <div className="tips">开启后，子账号将拥有管理员权限。</div>
        </section>
      ) : null}
    </main>

    <footer>
      <Button onClick={onFinish}>取消</Button>
      <Button type="primary" onClick={save} loading={saving}>
        保存
      </Button>
    </footer>
  </Spin>
}

const contentStyle = css`
  section {
    margin-bottom: 12px;
    padding-top: 0.5em;
    label {
      margin-right: 1.5em;
    }
    .tips {
      color: #999;
      font-size: 13px;
      margin-top: 4px;
    }
  }
`
